import { baseUrl } from './env'
import { uniLoading } from './loadWrap'
const request = (
	url,
	{
		method = 'get',
		data = {},
		dataType = 'json',
		header = {},
		isReject = true,
	}
) => {
	const token = uni.getStorageSync('token')
	const tenantId = uni.getStorageSync('orgId')
	const userId = uni.getStorageSync('userId')
	// console.log(baseUrl() + url)
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl() + url,
			method,
			data,
			dataType,
			header: {
				cookie: 'sessionType=APP;timeout=-1;point=uni_app',
				tenantId: tenantId,
				Authorization: token,
				userId: userId,
				// 'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
				'content-type': 'application/json',
				reqChannel: 100013,
				...header,
			},
			success: (res) => {
				if (res.data.success) {
					resolve(res.data)
				} else {
					if (res.data.code == 401) {
						uni.setStorageSync('token', '')
						uni.request({
							url: baseUrl() + 'user-web/wemini/silentLogin',
							data: {
								openId: uni.getStorageSync('openId'),
							},
							method: 'post',
							header: {
								'content-type': 'application/json', // 默认值
								reqChannel: 100013,
							},
							success(res) {
								let data = res.data
								if (data.success) {
									uni.setStorageSync('token', data.data.token)
									let rolesId =
										data.data.roles &&
										data.data.roles.length > 0
											? data.data.roles.map(
													(item) => item.id
											  )
											: []
									uni.setStorageSync('rolesId', rolesId)
									uni.setStorageSync(
										'orgId',
										data.data.belongId
									)
									uni.setStorageSync('userId', data.data.id)
									let pages = getCurrentPages()
									let currPage = pages[pages.length - 1]
									uni.reLaunch({
										url: currPage.$page.fullPath,
									})
								} else {
									uni.switchTab({
										url: '/pages/index/index',
									})
								}
							},
							fail(err) {
								reject(err)
							},
						})
					} else {
						if (Object.keys(res.data)) {
							return resolve(res.data)
						}
						if (isReject) {
							uni.showModal({
								title: '提示信息',
								content: res.data.message,
								showCancel: false,
							})
						}
					}
				}
			},
			fail(err) {
				reject(err)
			},
		})
	})
}
module.exports = {
	request: request,
	get: (
		url,
		opts,
		loadingOpt = {
			title: '加载中...',
		}
	) => {
		if (loadingOpt) {
			return uniLoading(
				request(url, {
					...opts,
					method: 'get',
				}),
				loadingOpt
			)
		} else {
			return request(url, {
				...opts,
				method: 'get',
			})
		}
	},
	post: (
		url,
		opts,
		loadingOpt = {
			title: '加载中...',
		}
	) => {
		if (loadingOpt) {
			return uniLoading(
				request(url, {
					...opts,
					method: 'post',
				}),
				loadingOpt
			)
		} else {
			return request(url, {
				...opts,
				method: 'post',
			})
		}
	},
}
